package com.framework.shiro;


import com.system.entity.SysUserEntity;
import com.system.service.ISysRoleMenuService;
import com.system.service.ISysUserRoleService;
import com.system.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * @author yz
 * @data: 2021/12/5 21:15 星期日
 * @file : UserRealm.java
 */
public class UserRealm extends AuthorizingRealm {


    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    private ISysRoleMenuService sysRoleMenuService;


    /*
        操作操作授权
     */

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        // 角色列表
        Set<String> roles = new HashSet<String>();
        // 功能列表
        Set<String> menus = new HashSet<String>();
        /*
        获取当前登录的用户对象
         */
        Subject subject = SecurityUtils.getSubject();
        //拿到 认证 传过来的user对象
        SysUserEntity user = (SysUserEntity) subject.getPrincipal();
        if (user.isAdmin()) {
            info.addRole("admin");
            info.addStringPermission("*:*:*");
        } else {
            roles = sysUserRoleService.selectRoleKeys(user.getUserId());
            menus = sysRoleMenuService.selectPermsByUserId(user.getUserId());
            info.setRoles(roles);
            info.setStringPermissions(menus);
        }

        return info;
    }

    /*
        登录对用户进行认真
        认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        /*
        获取数据库里的用户
         */
        SysUserEntity user = sysUserService.sysUserGetById(userToken.getUsername());
        // 用户名认证
        // 用户为null ,抛出异常 UnknownAccountException
        if (user == null) {
            return null;
        }

        //可以不要 只是用来判断用户登录后 隐藏登录按钮
//        Subject subject = SecurityUtils.getSubject();
//        Session session =subject.getSession();
//        session.setAttribute("login",user);


        //密码认证 ，shiro做 不需要我们做
        return new SimpleAuthenticationInfo(user, user.getPassword(), "");
    }
}
